package com.gxc.interceptor;

import com.gxc.enums.LoginEnums;
import com.gxc.utils.LogUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 登陆拦截器.
 *
 * @author 宫新程
 * @since 2018/12/15 4:54 PM
 */
public class LoginInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    // 输出登陆的日志
    String url = request.getRequestURL().toString();
    if (url.contains("/login")) {
      //LogUtils.showInterceptorLog(request);
      return true;
    }
    // 输出日志.
    //LogUtils.showInterceptorLog(request);
    // 从session中获取用户的登陆信息.
    HttpSession session = request.getSession();
    Object loginUser = session.getAttribute(LoginEnums.LOGIN_USER.getKey());
    // 如果没有登陆.
    if (loginUser == null) {
      response.sendRedirect(request.getServletContext().getContextPath() + "/page/login");
      return false;
    }
    return true;
  }

  @Override
  public void postHandle(
      HttpServletRequest request,
      HttpServletResponse response,
      Object handler,
      ModelAndView modelAndView)
      throws Exception {}

  @Override
  public void afterCompletion(
      HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
      throws Exception {}
}
